/**
 * 
 */
package uk.ac.ebi.curtain.utils.io.impl;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import uk.ac.ebi.curtain.utils.io.AbstractIO;

/**
 * @author mhaimel
 *
 */
public class FileIO extends AbstractIO{
	public static final String newLineSeparator = System.getProperty("line.separator");
	private static Log log = LogFactory.getLog(FileIO.class);
	
	public static void closeQuietly(Closeable obj){
		if(null != obj){
			try {
				obj.close();
			} catch (Exception e) {
				log.trace("Quiet close error:",e);
			}
		}
	}

	private final File file;
	private final boolean append;
	private CompressionFormat comp = null;

	public FileIO(File file) {
		this(file,false);
	}
	
	public FileIO(File file, boolean append) {
		this.file = file;
		this.append = append;
	}
	
	public RandomAccessFile getRandomAccessReader() throws IOException{
		return new RandomAccessFile(this.getFile(),"r");
	}
	
	public BufferedRafReader getBufferedRafReader() throws IOException{
		return new BufferedRafReader(this.getFile());
	}
	
	public BufferedRafReader getBufferedRafReader(int buffSize) throws IOException{
		return new BufferedRafReader(this.getFile(),buffSize);
	}
	
	public RandomAccessFile getRandomAccessWriter() throws IOException{
		return new RandomAccessFile(this.getFile(),"rw");
	}
//	public BufferedRaf getBufferedRafWriter() throws IOException{
//		return new BufferedRaf(this.getFile(),"rw");
//	}

	@Override
	protected InputStream getBaseInputStream() throws IOException {
		return new FileInputStream(getFile());
	}

	@Override
	protected OutputStream getBaseOutputStream() throws IOException {
		return new FileOutputStream(getFile(),append);
	}
	
	private CompressionFormat getCompression(){
		if(null == comp){
			comp = CompressionFormat.getCompression(this.getFile());
		}
		return comp;
	}
	
	public void setCompression(CompressionFormat comp){
		this.comp = comp;
	}

	private File getFile() {
		return file;
	}

	@Override
	protected CompressionFormat[] getStreamCompression() {
		CompressionFormat comp = getCompression();
		if(null == comp){
			return new CompressionFormat[0];
		} else {
			return new CompressionFormat[]{comp};
		}
	}
}
